import React from 'react'
import { Route, Switch, withRouter } from 'react-router-dom'
import Bundle from './Bundle'
import ErrorPage from '../Layout/ErrorPage'
import NotFound from '../Layout/NotFound'
import Loading from '../Layout/Loading'
import Pages from '../pages/page.router'
import { connect } from 'react-redux'
import layout from '../decorators/layout'

const createComponent = (component, title, noLayout) => () => (
  <Bundle load={component}>
    {Component => {
      if (Component) {
        document.title = title + '-' + document.title || ''
        //绑定loction，公共数据，layout等
        let MyComponent = !noLayout
          ? withRouter(connect()(layout(Component)))
          : withRouter(connect()(Component))
        return <MyComponent />
      }
      return <Loading />
    }}
  </Bundle>
)
export default () => (
  <Switch>
    {Pages.map(({ title, noLayout, path, component, exact }, index) => (
      <Route
        key={index}
        exact={exact}
        path={path}
        component={createComponent(component, title, noLayout)}
      />
    ))}
    {/*错误页面*/}
    <Route path="/error" component={ErrorPage} />
    {/*未找到页面，404*/}
    <Route component={NotFound} />
  </Switch>
)
